//
//  CS_MusicWifiFileStorage.swift
//  NewSS
//
//  Created by 杨馥瑞 on 2021/11/12.
//

class CS_MusicWifiFileStorage {
    
    static let shared = CS_MusicWifiFileStorage()
    private init() {
        _loadLocalFileName()
    }
    
    private var _allFileNames: [String] = [String]()
    private var _filePath = ""
    private var _relativeFilePath = ""
    
    // MARK: - 外部方法
    
    func isAlreadyExit(_ fileName: String) -> Bool {
        return _allFileNames.contains(fileName)
    }
    
    func moveFilePath(_ file: String, toDesPathWithName fileName: String) -> Bool {
        assert(FileManager.default.fileExists(atPath: file), "file not exist")
        if isAlreadyExit(fileName) {
            return false
        }
        let desPath = getStorePath().appendingPathComponent(fileName)
        do {
            try FileManager.default.moveItem(atPath: file, toPath: desPath)
            _allFileNames.append(fileName)
            return true
        } catch {
            print("文件移动失败：\(error.localizedDescription)")
            return false
        }
    }
    
    func removeFileName(_ fileName: String) {
        removeFileNames([fileName])
    }
    
    func removeFileNames(_ fileNames: [String]) {
        for fileName in fileNames {
            if fileName.isEmpty { continue }
            let desPath = getStorePath().appendingPathComponent(fileName)
            do {
                try FileManager.default.removeItem(atPath: desPath)
                _allFileNames = _allFileNames.filter { $0 != fileName }
            } catch {
                print("删除文件失败，文件名：\(fileName)，错误信息：\(error.localizedDescription)")
                _allFileNames = _allFileNames.filter { $0 != fileName }
            }
        }
    }
    
    func removeAllFile() {
        _allFileNames.forEach { [weak self] filename in
            self?.removeFileName(filename)
        }
    }
    
    @discardableResult
    func getStorePath() -> String {
        let relativePath = "download/wifiTransfer"
        _filePath = _FileManager.dirPathInLibrary(relativePath)
        let sandboxPath = NSHomeDirectory()
        _relativeFilePath = _filePath.replacingOccurrences(of: sandboxPath, with: "")
        return _filePath
    }
    
    @discardableResult
    func getStoreRelativePath() -> String {
        if _relativeFilePath.isEmpty {
            getStorePath()
        }
        return _relativeFilePath
    }
    
    func getAbsoluteFilePath(_ fileName: String) -> String {
        return getStorePath().appendingPathComponent(fileName)
    }
    
    // MARK: - 私有方法
    
    private func _loadLocalFileName() {
        if let subfiles = FileManager.default.subpaths(atPath: getStorePath()) {
            _allFileNames += subfiles
        }
    }
    
}

private struct _FileManager {
    
    static func libraryPath() -> String {
        let path = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true).first ?? ""
        
        if CJEnvConfig.shareInstance().env.rawValue == 0 {
            return "\(path)/TestRootDir"
        }
        else {
            return path
        }
    }
    
    static func dirPathInLibrary(_ dir: String) -> String {
        let path = libraryPath().appendingPathComponent(dir)
        do {
            try FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)
            addSkipBackupAttributeToItemPath(path)
            return path
        }
        catch {
            print("创建文件路径失败：\(error.localizedDescription)")
            return ""
        }
    }
    
    static func addSkipBackupAttributeToItemPath(_ filePath: String) {
        var url = URL(fileURLWithPath: filePath)
        assert(FileManager.default.fileExists(atPath: url.path))
        url.setTemporaryResourceValue(true, forKey: .isExcludedFromBackupKey)
    }
    
}

